package cn.zyjblogs.netty.dubborpc.netty;

import cn.zyjblogs.netty.dubborpc.constant.CommonConstant;
import cn.zyjblogs.netty.dubborpc.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

//服务器这边handler比较简单
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取客户端发送的消息并调用服务
        System.out.println("msg: "+msg);
        //客户端在调用服务器的api 时，我们需要定义一个协议
        //要求 每次发消息时都必须以某个字符串开头 “HelloService#hello#”
        if (msg.toString().startsWith(CommonConstant.FRE)){
            String hello = new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(hello);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       ctx.close();
    }
}
